package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"server/client/jwt"
	"server/config"
	"server/model"
	"server/model/response"
	"server/service"
	"strconv"
	"time"
)

//定义中间件函数
func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("X-Auth-Token")
		if token == "" {
			response.FailWithDetailed(gin.H{"reload": true}, "未登录或非法访问", c)
			c.Abort()
			return
		}

		if service.IsInBlacklist(token) {
			response.FailWithDetailed(gin.H{"reload": true}, "您的帐户异地登陆或令牌失效", c)
			c.Abort()
			return
		}

		j := jwt.JwtClient
		// parseToken 解析token包含的信息
		claims, err := j.ParseToken(token)
		if err != nil {
			if err == jwt.TokenExpired {
				response.FailWithDetailed(gin.H{"reload": true}, "授权已过期", c)
				c.Abort()
				return
			}
			response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
			c.Abort()
			return
		}
		//检查当前token中的用户信息是否存在，若不存在，注销改token
		if err, _ = service.FindUserByUuid(claims.UUID); err != nil {
			_ = service.SetBlacklist(model.Blacklist{Jwt: token})
			response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
			c.Abort()
		}

		if claims.ExpiresAt-time.Now().Unix() < claims.BufferTime {
			claims.ExpiresAt = time.Now().Unix() + 60*60*24*7
			newToken, _ := j.CreateToken(claims)
			newClaims, _ := j.ParseToken(newToken)
			c.Header("New-Token", newToken)
			c.Header("New-Expires-At", strconv.FormatInt(newClaims.ExpiresAt, 10))
			if config.GlobalConf.System.UseMultipoint {
				err, RedisJwtToken := service.GetRedisJWT(newClaims.Username)
				if err != nil {
					fmt.Printf("get jwt token form redis failed.error is %v\n", err)
				} else {
					//拉黑即将过期的老token
					_ = service.SetBlacklist(model.Blacklist{Jwt: RedisJwtToken})
				}
				// 更新新token到redis中
				_ = service.SetRedisJWT(newToken, newClaims.Username)
			}
		}
		c.Set("claims", claims)
		c.Next()
	}
}
